package com.gdk.ksoft.assembly.utils.system;

import android.graphics.Bitmap;
import android.text.TextUtils;

import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.listener.OnClearListener;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Mrper on 2014/11/25.
 * 文件辅助类
 */
public class FileUtils {

    /**
     * 把stream转换为string
     * @param is
     * @param encoding
     * @return
     * @throws Exception
     */
    public static String stream2string(InputStream is,String encoding) throws Exception{
        if(is == null)return null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,encoding));
        StringBuilder strBuilder = new StringBuilder();
        String lineContent = null;
        while((lineContent = reader.readLine())!=null){
            strBuilder.append(lineContent);
        }
        reader.close();
        return strBuilder.toString();
    }

    /**
     * 把stream转换为string
     * @param is
     * @return
     * @throws Exception
     */
    public static String stream2string(InputStream is) throws Exception{
        if(is == null)return null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder strBuilder = new StringBuilder();
        String lineContent = null;
        while((lineContent = reader.readLine())!=null){
            strBuilder.append(lineContent);
        }
        reader.close();
        return strBuilder.toString();
    }

    /**
     * 写入图片到文件
     * @param bmp
     * @param filename
     * @return
     */
    public static boolean writeImageToFile(Bitmap bmp,Bitmap.CompressFormat format,int quality,String filename) throws Exception{
        if(bmp == null || TextUtils.isEmpty(filename)){
            throw new Exception("参数不正确!");
        }
        File file = new File(filename);
        File fileParent = file.getParentFile();
        if(fileParent.isDirectory() || fileParent.mkdirs()){
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bmp.compress(format,quality,bos);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bos.toByteArray());
            fos.close();
            return true;
        }
        throw new Exception("文件保存异常!");
    }

    /**
     * 将字符串形式表示的十六进制数转换为byte数组
     */
    public static byte[] hexStringToBytes(String hexString)
    {
        hexString = hexString.toLowerCase();
        String[] hexStrings = hexString.split(" ");
        byte[] bytes = new byte[hexStrings.length];
        for (int i = 0; i < hexStrings.length; i++)
        {
            char[] hexChars = hexStrings[i].toCharArray();
            bytes[i] = (byte) (charToByte(hexChars[0]) << 4 | charToByte(hexChars[1]));
        }
        return bytes;
    }

    /**
     * Char类型转换为Byte类型
     * @param c
     * @return
     */
    private static byte charToByte(char c)
    {
        return (byte) "0123456789abcdef".indexOf(c);
    }

    /**
     * 获取文件尺寸
     * @param size
     * @return
     */
    public static String getFileSize(long size){
        String[] fileSizes = {"byte","KB","MB","GB","TB"};
        for(int i=0;i<fileSizes.length;i++){
            if(size<Math.pow(1024,i+1))
                return FormatUtils.exactNumber((double) size / Math.pow(1024, i), "0.00")+fileSizes[i];
        }
        return "";
    }



    /**
     * 清理缓存数据
     */
    public static void clearCache(String dirName,OnClearListener listener){
        File file = new File(dirName);
        if(file.isFile()){
            file.delete();
            if(listener!=null){
                listener.onClearListener(file.getAbsolutePath());
            }
        }else if(file.isDirectory()){
            File[] files = file.listFiles();
            for(File f : files){
                 FileUtils.clearCache(f.getAbsolutePath(),listener);
            }
            file.delete();
            if(listener!=null){
                listener.onClearListener(file.getAbsolutePath());
            }
        }
    }

}
